<template>
    <div style="height: 100%;width: 100%">
        <div class="preview-mobile" v-if="isMobile">
            <div class="mobile-content">
                <div class="mobile-content-layout">
                    <mobile-content :readOnly="false" :mobileLayout="mobileConfig" :screenConfig="screenConfig"
                                    :screenView="screenView"></mobile-content>
                </div>
            </div>
        </div>
        <div v-else style="height: 100%;width: 100%" id="freedom" @click="fullScreenId = ''">
            <div class="ScreenViewManageEdit-drag-common-img"
                 :style="{'background-color':screenConfig.globalConfig && screenConfig.globalConfig.background=='color'?screenConfig.globalConfig.customColor:''}">
                <img
                    v-if="screenConfig.globalConfig && screenConfig.globalConfig.background=='system' &&screenConfig.globalConfig.mode=='dark'"
                    class="system-img"
                    :src="getImage('image/background/dark'+screenConfig.globalConfig.bgImage+'.png')"/>
                <img
                    v-if="screenConfig.globalConfig && screenConfig.globalConfig.background=='system' &&screenConfig.globalConfig.mode=='bright'"
                    class="system-img"
                    :src="getImage('image/background/light'+screenConfig.globalConfig.bgImage+'.png')"/>
                <img v-else-if="screenConfig.globalConfig && screenConfig.globalConfig.background=='custom'"
                     class="system-img" :src="getFilePath(screenConfig.globalConfig.customImage)" alt="photo"/>
            </div>
            <rx-drag ref="drag" :dragList="screenConfig.components">
                <div v-for="(rect, index) in screenConfig.components" :key="index">
                    <rxDragList
                        :dragShow="dragShow"
                        :scrollWidth="scrollWidth"
                        :index="index"
                        @refresh="refresh($event,rect)"
                        :dragList="screenConfig.components"
                        :rect="rect">
                        <template v-slot:content>
                            <div @click.stop="rxEnlarge(rect.id)" style="position: relative" v-if="!rect.child"
                                 :class="[borderShow(rect.config.styles.background) || rect.config.styles.mode =='material' ||  rect.type== 'iconfont' ?'rx-dragList-common':'rx-dragList-common-system']"
                                 :style="getStyle(rect.config.styles,rect.type)">
                                <!-- 控件内容-->
                                <div @click.stop="enlarge(rect)"
                                     v-if="rect.id == fullScreenId && rect.config.styles.fullScreenShow && !fullScreenList.includes(rect.type)"
                                     class="fullscreen">
                                    <rx-icon-show icon="icon-linefullscreen"></rx-icon-show>
                                </div>
                                <component :is="rect.type+'-view'"
                                           style="z-index:1;position: absolute;"
                                           :ref="rect.id"
                                           :screenView="screenView"
                                           :screenConfig="screenConfig"
                                           :config="rect.config"
                                           :loadView="loadView"
                                ></component>
                            </div>
                            <div v-else>
                                <div @click.stop="rxEnlarge(rectChild.id)" v-for="(rectChild, index1) in rect.child"
                                     :key="index1">
                                    <rxDragList
                                        @refresh="refresh"
                                        :dragShow="dragShow"
                                        :scrollWidth="scrollWidth*rect.adaptWidth"
                                        :scrollChildHeight="rect.height"
                                        :index="index"
                                        :index1="index1"
                                        :dragList="screenConfig.components"
                                        :key="index1"
                                        :child='true'
                                        :rect="rectChild">
                                        <template v-slot:content>
                                            <div
                                                style="position: relative"
                                                :class="[borderShow(rectChild.config.styles.background) ||  rectChild.config.styles.mode =='material' ||  rectChild.type== 'iconfont' ?'rx-dragList-common':'rx-dragList-common-system']"
                                                :style="getStyle(rectChild.config.styles,rectChild.type)">
                                                <!-- 控件内容-->
                                                <div @click.stop="enlarge(rectChild)"
                                                     v-if="rectChild.id == fullScreenId && rectChild.config.styles.fullScreenShow && !fullScreenList.includes(rectChild.type)"
                                                     class="fullscreen">
                                                    <rx-icon-show icon="icon-linefullscreen"></rx-icon-show>
                                                </div>
                                                <component :is="rectChild.type+'-view'"
                                                           style="z-index:1;position: absolute;"
                                                           :ref="rectChild.id"
                                                           :screenView="screenView"
                                                           :screenConfig="screenConfig"
                                                           :config="rectChild.config"
                                                           :loadView="loadView"
                                                ></component>
                                            </div>
                                        </template>
                                    </rxDragList>
                                </div>
                            </div>
                        </template>
                    </rxDragList>
                </div>
            </rx-drag>
            <!--全屏弹窗-->
            <full-screen @minification="minification" v-if="fullScreenShow" :fullScreenShow="fullScreenShow"
                         :screenView="screenView" :screenConfig="screenConfig" :fullScreen="fullScreen"
                         :loadView="loadView"></full-screen>
        </div>
    </div>
</template>

<script>
import ScreenViewManageApi from '@/api/screen/core/screen-view-manage.js'
import previewComponents from "@/views/modules/preview/index.js";
import CustomComponents from "@/views/modules/custom-components/index.js";
import {Util, TokenUtil} from "@lowcode/jpaas-base-lib";
import {debounce} from "lodash-es";
import FullScreen from "@/views/modules/design/dialog/full-screen.vue";
import MobileContent from "@/views/modules/design/mobile/mobile-content.vue";
import PagePublicJs from "@/views/modules/js/page-public.js";
import { PublicFunction } from "@lowcode/jpaas-share-component";
import LoginApi from "../../../api/login";
export default {
    name: "screen-preview",
    components: {
        FullScreen,
        MobileContent,
    },
    mixins: [PagePublicJs, previewComponents, CustomComponents,PublicFunction],
    props: ["alias", "appId", "width", "isMobile", "isAuth"],
    data() {
        return {
            //大屏别名
            screenAlias: "",
            //大屏应用ID
            screenAppId: "",
            //大屏对象
            screenView: "",
            //大屏组件
            screenConfig: {},
            dragKey: new Date().getTime(),
            scrollWidth: 0,
            dragShow: true,//禁止拖拽
            //加密参数
            encryParams: {},
            fullScreen: {},//全屏列表
            fullScreenShow: false,
            fullScreenList: ['text', 'quillEditor', 'realTime', 'weather', 'image', 'iconfont', 'filter'],
            fullScreenId: '',
            mobileConfig: [],
            heartbeatInterval: null, // 用于存储定时器 ID
        }
    },
    created() {
        this.init();
        this.$nextTick(() => {
            this.initStyle();
        })
        // 组件挂载时启动定时器
        this.startHeartbeat();
    },
    methods: {
        i18n(name, text, key) {
            return this.$ti18(name, text, "previewLang", key);
        },
        refresh: debounce(function (ary) {
            this.screenConfig.components = ary;
            this.$forceUpdate();
        }, 1000),
        initStyle() {
            let freedomDiv = document.getElementById('freedom');
            if (freedomDiv) {
                this.scrollWidth = freedomDiv.scrollWidth;
            } else {
                this.scrollWidth = document.documentElement.clientWidth - 260
            }
            if (this.width) {
                this.scrollWidth = this.width
            }
            let self = this;
            window.onresize = () => {
                return (() => {
                    this.$nextTick(() => {
                        let freedomDiv = document.getElementById('freedom');
                        if (freedomDiv) {
                            this.scrollWidth = freedomDiv.scrollWidth;
                        }
                    });
                })();
            };
        },
        init() {
            if (this.appId) {
                this.screenAppId = this.appId;
            }
            if (this.alias) {
                this.screenAlias = this.alias;
            } else if (this.$route.params && this.$route.params.alias) {
                this.screenAlias = this.$route.params.alias;
            }
            if (!this.screenAlias) {
                this.$message.warning(this.i18n("aliasTips", "大屏标识不能为空！"));
                return;
            }
            ScreenViewManageApi.getByAlias(this.screenAlias, this.screenAppId, this.isAuth).then(res => {
                if (!res.success) {
                    this.$message.warning(res.message);
                    return;
                }
                if (res.data.jsScript) {
                    this.initJsScript(res.data.jsScript);
                }
                this.screenView = res.data;
                this.screenConfig = JSON.parse(this.screenView.config.replace(/\n/g, "\\n").replace(/\t/g, "\\t"));
                if (res.data.mobileConfig) {
                    this.mobileConfig = JSON.parse(res.data.mobileConfig)
                }
            });
        },
        getFilePath(fileId) {
            let token = TokenUtil.getToken();
            fileId = Util.encryptWord(fileId);
            return "/api/api-system/system/core/sysFile/previewFile?fileId=" + fileId + "&accessToken=" + token;
        },
        getStyle(type, rect) {
            if (!type.background || rect == ('image' || 'iconfont')) {
                return
            }
            if (type.background == 'system') {
                //系统自定义
                let img = this.getImage('/image/background/border' + type.bgImage + '.png')
                const style = {borderImageSource: 'url(' + img + ')'};
                return style;
            } else if (type.background == 'custom') {
                //上传图片
                let img = this.getFilePath(type.customImage)
                const style = {backgroundImage: 'url(' + img + ')', backgroundSize: '100%'};
                return style;
            } else if (type.background == 'color') {
                const style = {
                    background: type.customColor,
                    border: this.initBorder(type),
                    borderRadius: type.borderRadius + 'px'
                };
                return style;
            }
        },
        initBorder(type) {
            if (type.borderOpacity === 0) {
                return 'nome'
            } else {
                return type.borderWidth + "px solid " + type.borderColor
            }
        },
        //判断是否展示边框
        borderShow(type) {
            let list = ['none', 'color', 'custom'];
            if (list.indexOf(type) != -1) {
                return true
            } else {
                return false
            }
        },
        //放大全屏
        enlarge(obj) {
            this.fullScreen = obj;
            this.fullScreenShow = true
        },
        minification() {
            this.fullScreenShow = false
        },
        rxEnlarge(id) {
            this.fullScreenId = id
        },
        getImage(url) {
            return import.meta.env.JPAAS_BASE_URL + '/' + url;
        },
        startHeartbeat() {
            // 每 10 分钟调用一次 heartbeat 方法
            this.heartbeatInterval = setInterval(() => {
                this.heartbeat();
            }, 10 * 60 * 1000);

            // 立即调用一次 heartbeat
            this.heartbeat();
        },
        stopHeartbeat() {
            // 清除定时器
            if (this.heartbeatInterval) {
                clearInterval(this.heartbeatInterval);
                this.heartbeatInterval = null;
            }
        },
        heartbeat() {
            LoginApi.getUserInfo().then(res=>{})
        },
    },
    beforeDestroy() {
        // 组件销毁前清除定时器
        this.stopHeartbeat();
    },
}
</script>

<style scoped>
.preview-mobile {
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
}

.fullscreen {
    font-size: 22px;
    cursor: pointer;
    background-color: #4285f4;
    color: white;
    position: absolute;
    top: 0px;
    right: 0px;
    z-index: 9999;
    width: 40px;
    height: 40px;
    text-align: center;
    line-height: 40px;
    border-radius: 5px;
    cursor: pointer;
}

.rx-dragList-common {
    width: 100%;
    height: 100%;
}

.rx-dragList-common-system {
    width: 100%;
    height: 100%;
    border-image-slice: 15 fill;
    border-width: 15px;
    border-style: solid;
    background-clip: padding-box;
    filter: blur(0px
    );
}

.ScreenViewManageEdit-drag-common-img {
    position: absolute;
    top: 0px;
    left: 0px;
    bottom: 0px;
    right: 0px;
    width: 100%;
    height: 100%;
}

.system-img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.mobile-content {
    width: 380px;
    height: 100%;
    padding: 10px;
    background-image: url("@img/mobile.png");
    background-size: 100% 100%;
}

.mobile-content-layout {
    width: 100%;
    margin-top: 30px;
    height: calc(100% - 50px);
    padding-top: 10px;
}
</style>
